<?php
/**
 * Created by PhpStorm.
 * User: meng
 * Date: 2023/9/5
 * Time: 15:26
 */

namespace lib\common;

use lib\exception\HttpResponseException;
use support\Request;

class CommonController
{
    /**
     * @var Request|null
     */
    protected Request $request;
    public function __construct () {
        $this->request = request();
    }

    final public function output ($message, $data, $code) {
        $responseParam = [
            'code'    => $code,
            'message' => $message
        ];
        $responseParam['data'] = $data;
        $response = json($responseParam);

        throw new HttpResponseException($response);
    }

    protected final function success ($message = null, $data = null): void {
        $responseMessage = 'success';
        $responseData = null;
        if (is_string($message)) {
            $responseMessage = $message;
            $responseData = $data;
        } else if (is_array($message) || is_object($message)) {
            $responseData = $message;
        }
        $this->output($responseMessage, $responseData, $this->code ?? 200);
    }

    protected final function fail ($message = null, $data = null): void {
        $responseMessage = 'fail';
        $responseData = null;
        if (is_string($message)) {
            $responseMessage = $message;
            $responseData = $data;
        } else if (is_array($message) || is_object($message)) {
            $responseData = $message;
        }
        $this->output($responseMessage, $responseData, $this->code ?? 400);
    }
}
